package control;

import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.User;
import model.UserJpaController;

public class MainPage extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String userId = null;
        HttpSession ses = request.getSession();
        userId = (String)ses.getAttribute("userId");
        System.out.println("UserId " +userId);
            if (userId == null) {
                response.sendRedirect("index.jsp");
            }
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("WebApplication1PU");
            EntityManager em = emf.createEntityManager();
            User user;
            // finds user with primary key userId
            UserJpaController userControl = new UserJpaController(emf);
            user = userControl.findUser(Integer.parseInt(userId));
            request.setAttribute("userId", userId+"");
            request.setAttribute("name", user.getName());
            request.setAttribute("surname", user.getSurname());
            request.setAttribute("group", user.getGrp());
            request.setAttribute("imagePath", user.getImagePath());
            
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/MainPage.jsp");
            rd.include(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
